import type { Dept, IDept } from '@/types/dept'
import request from './request'

export function getDeptList() {
  return request({
    url: '/sys/dept/list',
    method: 'get'
  }).then(({ deptList }) => {
    const list = arr2tree(deptList)
    return { list }
  })
}


function arr2tree(arr: IDept[], parentId = 0) {
  const arrMap = arr.reduce((pre, cur) => {
    pre[cur.deptId] = cur
    return pre
  }, {} as Record<string, IDept>)
  const root: IDept[] = [] 
  arr.forEach(item => {
    if (item.parentId === parentId) {
      root.push(item);
    } else {
      const parent = arrMap[item.parentId]
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(item)
    }
  })
  return root
}

export function saveDept(data: Dept) {
  return request({
    url: `/sys/dept/${data.deptId ? 'update' : 'save'}`,
    method: 'post',
    data
  })
}

export function deleteDept(deptId: number) {
  return request({
    url: '/sys/dept/delete',
    method: 'post',
    data: { deptId },
    headers: {
      'content-type': 'application/x-www-form-urlencoded' 
    }
  })
}